//
//  AlbumController.m
//  Created by trung dq 
//

#import "AlbumController.h"  
#import "PhotoSource.h"  
#import "Photo.h" 
#import "user_image.h"
#import "Request.h"
#import "AppDelegate.h"
#import "User.h"
#import "AlbumsFacebookViewController.h"
#import "JGoAPI.h"
#import "Utility.h"

@implementation AlbumController  

@synthesize images,photos;  
@synthesize navController;
@synthesize uiasView;
@synthesize imgPicker;
//@synthesize isAvatar;
//@synthesize onlyShow = _onlyShow;
@synthesize type = _type;

#pragma mark -
#pragma mark Custom

-(void)createPhotos 
{
    
    if (/*!self.onlyShow*/ self.type != AlbumForPeople) {
        int numbersImg = [self.photos count] + 1;
        images = [[NSMutableArray alloc] initWithCapacity:numbersImg];
        [images addObject:[[[Photo alloc] initWithURL:@"bundle://add-photo.png"
                                             smallURL:@"bundle://add-photo.png"
                                                 size:CGSizeMake(0, 0)] autorelease]];
    }
    else {
         images = [[NSMutableArray alloc] initWithCapacity:[self.photos count]];
    }
    
    for (NSDictionary *aPhoto in self.photos) {
        NSString *thumbUrl  = [NSString stringWithFormat:@"%@/%@",JGO_HOST,[aPhoto objectForKey:@"thumb"]];
        NSString *url  = [NSString stringWithFormat:@"%@/%@",JGO_HOST,[aPhoto objectForKey:@"image"]];        
        LOG(@"Image URL: %@",url);
        
        [images addObject: [[[Photo alloc] initWithURL:url
                                              smallURL:thumbUrl
                                                  size:CGSizeMake(0, 0)] autorelease]];
        
    }
    
}

- (void)setPhotoSourceAgain 
{
    NSLog(@"PhotoList: %@",photos);
    [self createPhotos];
    self.photoSource = nil;
    self.photoSource = [[PhotoSource alloc]  
                        initWithType:PhotoSourceNormal  
                        title:@"Photos"  
                        photos:images  
                        photos2:nil  
                        ];
    

}


- (void)presentView
{
    
    [UIView animateWithDuration:0.60f animations:^{
        
        CGRect uiasViewFrame   = self.uiasView.frame;
        uiasViewFrame.origin.y = (self.view.frame.size.height - kUIASHeight);
        
        self.uiasView.frame = uiasViewFrame;
    }];
    
    //self.presentASButton.enabled = NO;
}
- (void)dismissView {
    
    [UIView animateWithDuration:0.75f animations:^{
        
        CGRect uiasViewFrame   = self.uiasView.frame;
        uiasViewFrame.origin.y = (self.view.frame.size.height + kUIASHeight);
        
        self.uiasView.frame = uiasViewFrame;
    }];
    
    //self.presentASButton.enabled = YES;
}


-(void)delayUploadPhoto:(MBProgressHUD*)progress 
{    
    NSString *userId = [[JGoUtility sharedCreateAccount] objectForKey:@"user_id"];   
        
    NSData *avatarData = UIImageJPEGRepresentation(imageData, 0.2);
    NSError *error = nil;    
    
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    
    [JGoAPI uploadPhotoWithUserId:userId avatarData:avatarData error:&error];
    
    if (!error) {
                
        NSError *error = nil;
        NSArray *arrayPhoto = [JGoAPI getPhotoWithUserId:userId error:&error];
        
        [self setPhotos:(id)arrayPhoto];
        [self setPhotoSourceAgain];
        [self.tableView reloadData];       
    }
    else {
        [JGoUtility showAlert:[error localizedDescription]];
    }
    
    [progress hide:YES];
    
    [UIApplication sharedApplication].idleTimerDisabled = NO;
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo 
{
	imageData = nil;
    imageData = [img retain];	
	[picker dismissModalViewControllerAnimated:YES];        
    
    [JGoUtility showProgressInView:self.view 
                            target:self 
                             title:@"Uploading photo..." 
                          selector:@selector(delayUploadPhoto:)];
    
}

-(void)addFromFB
{
    isRefresh = YES;
    AlbumsFacebookViewController *aFBVC = [[AlbumsFacebookViewController alloc]initWithNibName:@"AlbumsFacebookViewController" bundle:nil];
    aFBVC.albumVC = self;
    [self.navController pushViewController:aFBVC animated:YES];
    [aFBVC release];
    [self dismissView];
}

-(void)addFromPhone
{
    isRefresh = NO;
    imgPicker.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentModalViewController:self.imgPicker animated:YES];
    
    [self dismissView];
}

-(void)takePhoto
{
    isRefresh = NO;
    imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentModalViewController:imgPicker animated:YES];
    [self dismissView];
}



-(void) backPressed 
{
    [self.navigationController popViewControllerAnimated:YES];
        
}

- (void)setTitle:(NSString*)title
{       
    UILabel * label = [[[UILabel alloc] initWithFrame:CGRectMake(0,0,320,43)] autorelease];
	label.textColor = [UIColor blackColor];
	label.backgroundColor = [UIColor clearColor]; 
	label.text = title;
    label.textColor = [UIColor colorWithRed:0.573 green:0.573 blue:0.573 alpha:1];
	self.navigationItem.titleView = label;
	[label sizeToFit];    
}

-(void)initNavigationBar 
{
    self.navigationController.navigationBar.hidden = NO;
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    UIView *overlayView = [[UIView alloc] initWithFrame:CGRectMake(0, 43, 320, 1)];
    [overlayView setBackgroundColor:[UIColor whiteColor]];
    [self.navigationController.navigationBar addSubview:overlayView]; // navBar is your UINavigationBar instance
    [overlayView release];
    
    UIButton *BtnBack = [UIButton buttonWithType:UIButtonTypeCustom];
    BtnBack.frame = CGRectMake(0, 0, 29, 29);
    [BtnBack setImage:[UIImage imageNamed:@"back-button.png"] forState:UIControlStateNormal];
    [BtnBack addTarget:self action:@selector(backPressed) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:BtnBack];
    self.navigationItem.leftBarButtonItem =backItem;
    [backItem release];
    
    [self.tableView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bg.png"]]]; 
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
}

-(void)viewWillAppear:(BOOL)animated 
{
	
	[super viewWillAppear:animated];
    [self initNavigationBar];
    [self setTitle:@"Photos"];
    
    if (isRefresh && /*!_onlyShow*/ self.type != AlbumForPeople) {
        isRefresh = NO;
        [JGoUtility showProgressInView:self.view 
                                target:self 
                                 title:@"Reloading..." 
                              selector:@selector(delayLoadPhoto:)];
    }
    
	UINavigationController* navControllerAlbum = self.navController;
	navControllerAlbum.navigationBar.barStyle = UIBarStyleBlackOpaque;
	
	[self setWantsFullScreenLayout:YES];
	
}
- (void) updateTableLayout {
	
	self.tableView.contentInset = UIEdgeInsetsMake(5, 0, 0, 0);
	self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(TTBarsHeight(), 0, 0, 0);
}


- (void)thumbsTableViewCell:(TTThumbsTableViewCell*)cell didSelectPhoto:(id<TTPhoto>)photo 
{
    if (self.type == AlbumForAvatar || self.type == AlbumForShare) {
        
        if ([photo index] == 0 && /*!_onlyShow*/ (self.type != AlbumForPeople)) {
            [self presentView];
        }
        else {
            NSString *urlStr = [photo URLForVersion:TTPhotoVersionLarge];
            NSString *subStr = [NSString stringWithFormat:@"%@/",JGO_HOST];
            NSString *avatarURL;
            NSRange rangeOfSubstring = [urlStr rangeOfString:subStr];

            avatarURL = [urlStr substringFromIndex:rangeOfSubstring.length];
            [[JGoUtility sharedCreateAccount] setValue:avatarURL forKey:@"thumb"];
            
            if (self.type == AlbumForAvatar) {
            
                UIImage *imageAvatar = [[TTURLCache sharedCache] imageForURL:urlStr];
                
                if (imageAvatar) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:JGO_PROFILE_RELOAD_AVATAR 
                                                                        object:[NSDictionary dictionaryWithObject:imageAvatar 
                                                                                                           forKey:@"avatar"]];
                    [self.navigationController popViewControllerAnimated:YES];
                }
                else {
                    [[NSNotificationCenter defaultCenter] postNotificationName:JGO_PROFILE_RELOAD_AVATAR 
                                                                        object:nil];
                    
                    [self.navigationController popViewControllerAnimated:YES];   
                }
            }
            else if (self.type == AlbumForShare) {
                
                if ([self.ownerDelegate respondsToSelector:@selector(albumController:didSelectWithURL:)]) {
                    [self.ownerDelegate albumController:self didSelectWithURL:urlStr];
                }
            }
        }
    }
    else {
        
        if ([photo index] == 0 && /*!_onlyShow*/ (self.type != AlbumForPeople)) {
            [self presentView];
        }else {
            isRefresh = NO;
            [_delegate thumbsViewController:self didSelectPhoto:photo];
            
            BOOL shouldNavigate = YES;
            if ([_delegate respondsToSelector:@selector(thumbsViewController:shouldNavigateToPhoto:)]) {
                shouldNavigate = [_delegate thumbsViewController:self shouldNavigateToPhoto:photo];
            }
            
            if (shouldNavigate) {
                
                NSString* URL = nil;
                if (URL) {
                    TTOpenURLFromView(URL, self.view);
                    
                } else {
                    TTPhotoViewController* controller = [self createPhotoViewController];
                    controller.centerPhoto = photo;
                    [self.navController pushViewController:controller animated:YES];
                }
            }
        }
    }    
}

- (void)dealloc {
    [images release];
    [photos release];
    [imgPicker release];
    [uiasView release];
    [imageData release];
    self.navController = nil;
    [super dealloc];
}


- (void)viewDidLoad 
{
    isRefresh = NO;
	[self createPhotos]; // method to set up the photos array  
	self.photoSource = [[PhotoSource alloc]  
						initWithType:PhotoSourceNormal  
						title:@"Photos"  
						photos:images  
						photos2:nil  
						];
    
    
    NSArray *buttonArr = [NSArray arrayWithObjects:@"Add from Facebook",@"Add from Phone",@"Take Photo", nil];
    self.uiasView = [[CustomUIASView alloc] initWithFrameAndSource:CGRectMake(0, (self.view.frame.size.height + kUIASHeight), 320, 300) buttonTitles:buttonArr moreThreeButton:NO];
    
    [self.uiasView.firstButton addTarget:self action:@selector(addFromFB) forControlEvents:UIControlEventTouchUpInside];
    [self.uiasView.secondButton addTarget:self action:@selector(addFromPhone) forControlEvents:UIControlEventTouchUpInside];
    [self.uiasView.thirdButton addTarget:self action:@selector(takePhoto) forControlEvents:UIControlEventTouchUpInside];
    [self.uiasView.cancelButton addTarget:self action:@selector(dismissView) forControlEvents:UIControlEventTouchUpInside];
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
	//check if it is connected via facebook
    
    NSString *fb_accesToken = [prefs objectForKey:@"FBAccessTokenKey"];
    NSDate *fb_expire = [prefs objectForKey:@"FBExpirationDateKey"];
    
    if(fb_accesToken == nil && fb_expire == nil) {
        self.uiasView.firstButton.enabled = NO;
    }
    
    [self.view addSubview:self.uiasView];
    
    // Set up the image picker controller and add it to the view
    imgPicker = [[UIImagePickerController alloc] init];
    //self.imgPicker.allowsImageEditing = YES;
    imgPicker.delegate = self;    	
} 

- (void)delayLoadPhoto:(MBProgressHUD*)progess
{         
    NSError *error = nil;
    NSArray *getphotos = nil;
    NSDictionary *userInfo = [JGoUtility sharedCreateAccount];        
    
    getphotos = [JGoAPI getPhotoWithUserId:[userInfo objectForKey:@"user_id"] error:&error];        
    
    if (!error) {                
        [self setPhotos:(id)getphotos];
        [self setPhotoSourceAgain];
        [self.tableView reloadData];
    }
    else {
        [JGoUtility showAlert:[error localizedDescription]];
    }
    
    [progess hide:YES];
}


@end
